package com.yu.dv.strategy.metadata.impl;

import com.yu.dv.entity.TableInfo;
import com.yu.dv.strategy.metadata.MetadataTemplate;
import lombok.extern.slf4j.Slf4j;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class MySQLMetadataStrategy extends MetadataTemplate {

    @Override
    protected String getCatalog(Connection connection) throws Exception {
        return connection.getCatalog(); // MySQL返回数据库名
    }

    @Override
    protected String getSchema(Connection connection){
        return null; // MySQL通常不使用schema
    }

    @Override
    protected String[] getTableTypes() {
        return new String[]{"TABLE", "VIEW"};
    }

    @Override
    protected List<TableInfo> getTablesWithFallback(Connection connection, String catalog, String schema) throws Exception {
        List<TableInfo> tables = new ArrayList<>();

        String query = "SELECT TABLE_NAME, TABLE_TYPE, TABLE_COMMENT as REMARKS " +
                "FROM INFORMATION_SCHEMA.TABLES " +
                "WHERE TABLE_SCHEMA = DATABASE() AND TABLE_TYPE IN ('BASE TABLE', 'VIEW')";

        try (Statement stmt = connection.createStatement();
             ResultSet rs = stmt.executeQuery(query)) {

            while (rs.next()) {
                String tableName = rs.getString("TABLE_NAME");
                String tableType = rs.getString("TABLE_TYPE");
                String remarks = rs.getString("REMARKS");

                TableInfo table = new TableInfo(tableName, tableType, remarks);
                tables.add(table);
            }
        }

        log.info("MySQL备用方案获取到 {} 张表", tables.size());
        return tables;
    }
}